/**
 * 
 */
package com.fsharemobile.client;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.util.Map;

import com.squareup.okhttp.OkHttpClient;

/**
 * @author RAD-Dungtm9
 * 
 */
public class HttpUtil {

	public HttpUtil() {
		super();
		this.client = new OkHttpClient();		
	}

	private OkHttpClient client = null;

	// private List<String> cookie_values = null;

	public HttpResponse post(HttpRequest request) throws IOException {
		// byte[] b = body.getBytes(Charset.forName("UTF-8"));
		HttpURLConnection connection = client.open(request.getUrl());
		OutputStream out = null;
		InputStream in = null;
		HttpResponse response = null;
		try {
			// Write the request.
			connection.setRequestMethod("POST");
			// if (cookie_values != null) {
			// connection.setRequestProperty("Cookie",
			// TextUtils.join(";", cookie_values.toArray()));
			// }
			// set header
			for (Map.Entry<String, String> entry : request
					.getAddedHeaderFields().entrySet()) {
				connection.setRequestProperty(entry.getKey(), entry.getValue());
			}
			out = connection.getOutputStream();
			out.write(request.getBody());
			out.close();

			// Read the response.
			response = new HttpResponse();
			response.setHttpCode(connection.getResponseCode());
			if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
				throw new IOException("Unexpected HTTP response: "
						+ connection.getResponseCode() + " "
						+ connection.getResponseMessage());
			}			
			in = connection.getInputStream();
			byte[] body = readFully(in);
			response.setBody(body);
			response.setHeaderFields(connection.getHeaderFields());
			return response;
		} finally {
			// Clean up.
			if (out != null)
				out.close();
			if (in != null)
				in.close();
		}
	}

	public HttpResponse get(HttpRequest request) throws IOException {
		HttpURLConnection connection = client.open(request.getUrl());
		InputStream in = null;
		try {
			// set header
			for (Map.Entry<String, String> entry : request
					.getAddedHeaderFields().entrySet()) {
				connection.setRequestProperty(entry.getKey(), entry.getValue());
			}
			// Read the response.
			// connection.setRequestProperty("Cookie",
			// "session_id=e0m6tdrh3jqj8inlapg9758dq7");
			// if (cookie_values != null) {
			// // TODO
			// String test = TextUtils.join(";", cookie_values.toArray());
			// connection.setRequestProperty("Cookie",
			// TextUtils.join(";", cookie_values.toArray()));
			// }
			in = connection.getInputStream();
			HttpResponse response = null;
			response = new HttpResponse();
			// Read the response.
			response = new HttpResponse();
			response.setHttpCode(connection.getResponseCode());
			if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
				throw new IOException("Unexpected HTTP response: "
						+ connection.getResponseCode() + " "
						+ connection.getResponseMessage());
			}
			byte[] body = readFully(in);			
			response.setBody(body);
			response.setHeaderFields(connection.getHeaderFields());			
			return response;
		} finally {
			if (in != null)
				in.close();
		}
	}

	public static byte[] readFully(InputStream in) throws IOException {			
		/*ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		for (int count; (count = in.read(buffer)) != -1;) {
			out.write(buffer, 0, count);
		}
		return out.toByteArray();*/
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {			
			byte[] buf = new byte[1024];
			int read = in.read(buf);
			while (read > 0) {
				out.write(buf, 0, read);
				read = in.read(buf);
			}
		} finally {
			if (in != null) {				
				in.close();				
			}			
			if (out != null) {				
				out.close();				
			}
			// end update
		}
		return out.toByteArray();
	}
	
	String readFirstLine(InputStream in) throws IOException {
	    BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
	    StringBuffer result = new StringBuffer("");
	    String line = "";	    
	    while ((line = reader.readLine())!= null) {
	    	result.append(line);
	    }
	    return result.toString();
	  }
		

	// private static String readFirstLine(InputStream in) throws IOException {
	// BufferedReader reader = new BufferedReader(new InputStreamReader(in,
	// "UTF-8"));
	// return reader.readLine();
	// }

}
